import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { Modal, Spin, Button, Space } from 'antd';
import { PrinterOutlined } from '@ant-design/icons';

// const preview: React.FC =forwardRef (props, ref) => {
const ChildComp = (props, ref) => {
  const [visible, handleVisible] = useState<boolean>(false);
  const [waitShowPrinter, handleWaitShowPrintere] = useState<boolean>(false);
  const [spinning, handleSpinning] = useState<boolean>(true);
  // 纸张宽 mm
  const [width, handleWidth] = useState<string>('0');
  // 模板
  const [hiprintTemplate, handleHiprintTemplate] = useState<object>();
  // 数据
  const [printData, handlePrintData] = useState<object>();
  //   关闭
  function hideModal() {
    handleVisible(false);
  }
  function print() {
    handleWaitShowPrintere(true);
    hiprintTemplate?.print(
      printData,
      {},
      {
        callback: () => {
          handleWaitShowPrintere(false);
        },
      },
    );
  }
  // function toPdf() {
  //   hiprintTemplate?.toPdf(printData, '打印预览pdf');
  // }
  function show(hiprintTemplate, printData, width = '222') {
    handleVisible(true);
    handleSpinning(true);
    handleWidth(width + 12);
    handleHiprintTemplate(hiprintTemplate);
    handlePrintData(printData);
    console.log('预览', hiprintTemplate);
    setTimeout(() => {
      $('#preview_content').html(hiprintTemplate.getHtml(printData));
      handleSpinning(false);
    }, 500);
  }
  useImperativeHandle(ref, () => ({
    show,
  }));
  return (
    <div>
      <Modal
        visible={visible}
        maskClosable={false}
        onCancel={hideModal}
        width={width + 'mm'}
        title={
          <Space>
            <div style={{ marginRight: '20px' }}>打印预览</div>
            <Button
              loading={waitShowPrinter}
              type="primary"
              onClick={() => {
                print();
              }}
            >
              <PrinterOutlined />
              打印
            </Button>
            {/* <Button
              type="primary"
              onClick={() => {
                toPdf();
              }}
            >
              <PrinterOutlined />
              pdf
            </Button> */}
          </Space>
        }
        footer={[
          <Button
            key="close"
            onClick={() => {
              hideModal();
            }}
          >
            关闭
          </Button>,
        ]}
      >
        {/* 打印内容区域 */}
        <Spin spinning={spinning} style={{ minHeight: '100px' }}>
          <div id="preview_content" />
        </Spin>
      </Modal>
    </div>
  );
};

// ChildComp = forwardRef(preview);
export default forwardRef(ChildComp);
